import java.util.Arrays;
/**
 * This class is a subclass of the Hand class, and are used to model a hand of Straight Flush.
 * It overrides getTopCard,isValid and getType method that it inherits from Hand class.
 *
 * @author Jiang Feiyu
 *
 */
public class StraightFlush extends Hand{
    /**
     * Constructor for the StraightFlush type hand. Calls the constructor of Hand superclass.
     *
     * @param player Player who plays the hand
     * @param cards  List of card played by the player
     */
    public StraightFlush(CardGamePlayer player, CardList cards) {
        super(player, cards);
    }
    /**
     * Returns the top card of the hand.
     * The card with the highest rank in a straight flush is referred to as the top card of this straight flush.
     */
    public Card getTopCard() {
        int returnIndex = 0;
        int largest_card = 0;
        for(int i = 0;i < 5;i ++) {
            int this_rank = 0;
            if (this.getCard(i).getRank() == 0){
                this_rank = 13;
            }
            if (this.getCard(i).getRank() == 1){
                this_rank = 14;
            }
            if (this_rank > largest_card){
                largest_card = this_rank;
                returnIndex = i;
            }
        }
        return this.getCard(returnIndex);
    }
    /**
     * Checks whether the hand is a Straight Flush.
     */
    public boolean isValid() {
        if(this.size() == 5) {
            if ((this.getCard(1).getSuit() == this.getCard(2).getSuit()) && (this.getCard(2).getSuit() ==
                    this.getCard(3).getSuit()) && (this.getCard(3).getSuit() == this.getCard(4).getSuit()) &&
                    (this.getCard(4).getSuit() == this.getCard(5).getSuit())){
                int[] handranks = new int[5];
                for (int i = 0; i < handranks.length; i ++){
                    handranks[i] = this.getCard(i).getRank();
                }
                // Sort rank A and 2
                for(int i =0;i < 5; i++) {
                    int handrank = handranks[i];
                    switch (handrank) {
                        case 0:
                            handranks[i] = 13;
                        case 1:
                            handranks[i] = 14;
                        default:
                            handranks[i] = handrank;
                    }
                }
                // check whether it is consecutive
                Arrays.sort(handranks);
                for(int i = 0;i < 4;i++){
                    if (i == 3){
                        return handranks[i] == handranks[i + 1];
                    }
                    else{
                        if (handranks[i] != handranks[i + 1]){
                            return false;
                        }
                    }
                }
            }
        }
        return false;
    }
}
